package com.ljy.my_study.zookeeper使用;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/** 
* @author James
* @date 2018年6月5日 
*/
public class ZooKeeper_create_api_sync_usage implements Watcher{

	private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

	public static void main(String[] args) throws Exception {
		ZooKeeper zk = new ZooKeeper("192.168.0.102:2181", 1000, new ZooKeeper_create_api_sync_usage());
		connectedSemaphore.await();
//		String path1=zk.create("/zk-test1","test1".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
//		System.out.println("Success create znode:"+path1);
//		System.out.println("---------------------------------");
		String path12=zk.create("/zk-test1/test2","test1/test2".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
		System.out.println("Success create znode:"+path12);
		System.out.println("---------------------------------");
		String path2=zk.create("/zk-test2","test2".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
		System.out.println("Success create znode:"+path2);
		System.out.println("---------------------------------");
		String path3=zk.create("/zk-test3","test3".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
		System.out.println("Success create znode:"+path3);
		
		System.out.println("---------------------------------");
		long sessionId=zk.getSessionId();
		byte[] pwdArr=zk.getSessionPasswd();
		Thread.sleep(1000);
		long start=System.currentTimeMillis();
		ZooKeeper zk2 = new ZooKeeper("192.168.0.102:2181", 50000, new ZooKeeper_create_api_sync_usage(),sessionId,pwdArr,true);
		String path4=zk2.create("/zk-test4","test4".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
		System.out.println("Success create znode:"+path4);
		zk2.getChildren("/zk-test1", true,new IChileren2Callback(),null);
		long end=System.currentTimeMillis();
		System.out.println((end-start)+"ms");
	}
	
	@Override
	public void process(WatchedEvent event) {
		System.out.println(event.toString());
		if(KeeperState.SyncConnected==event.getState()) {
			connectedSemaphore.countDown();
		}
	}
	
	static class IChileren2Callback implements AsyncCallback.Children2Callback{

		@Override
		public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
			System.out.println("Get Children znode result:[response code:"+rc+",path:"+path+",ctx:"+ctx+",children list:"+children+",stat:"+stat+"]");
		}
		
	}

}
